#!/usr/bin/env bash
# Copyright (C) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in project root for information.

. "$(dirname "${BASH_SOURCE[0]}")/../../runme"
@ "shared.sh"

PRDIR="$BASEDIR/.build-pr"
_md "$PRDIR"

# make it possible to use the main version of these files later too
_ cp -a "$TOOLSDIR/build-pr" "$PRDIR/build-pr"

if [[ "$BUILDPR" = "" ]]; then exit 0; fi

echo "##[section] PR Build for #$BUILDPR"

get_pr_info
repourl="https://github.com/$REPO"

printf 'PR BUILD for #%s\n  repo: %s\n  ref: %s\n  sha1: %s\n' \
       "$BUILDPR" "$REPO" "$REF" "$SHA1"

git checkout "master" > /dev/null 2>&1
oldbr="$(git for-each-ref --format="%(refname:short)" "refs/heads/pr-*")"
if [[ -n "$oldbr" ]]; then git branch -D "$oldbr"; fi

text="A build has started."
post_status "pending" "$text"
post_comment "$text"

_get_T
git fetch "https://$T@github.com/$REPO" "$REF:refs/heads/pr-$BUILDPR"
git checkout "pr-$BUILDPR"
git reset --hard "$SHA1"

# useful info in build
{ printf '### This is a build for %s, changes:\n\n' "[github PR #$BUILDPR]($GURL)"
  git log --format="* [[%h]($repourl/commit/%H)] [%aN](mailto:%aE) %s" \
      "origin/master..$SHA1"
  printf '\n---\n'
  } > "$PRDIR/PR-Build.md"

# variable overrides
prvar() { printf '%s=%q\n' "$1" "$2" >> "$TOOLSDIR/local-config.sh"; }
prvar BUILD_SOURCEVERSION        "$SHA1"
prvar BUILD_REPOSITORY_NAME      "$REPO"
prvar BUILD_REPOSITORY_ID        "$repourl"
prvar BUILD_REPOSITORY_URI       "$repourl"
prvar BUILD_SOURCEBRANCH         "refs/heads/$REF"
prvar BUILD_SOURCEBRANCHNAME     "$(basename "$REF")"
prvar BUILD_SOURCEVERSIONAUTHOR  "$(git log -1 --format="%aN <%aE>")"
prvar BUILD_SOURCEVERSIONMESSAGE "$(git log -1 --format="%s")"
prvar BUILD_INFO_EXTRA_MARKDOWN  "$PRDIR/PR-Build.md"
